package europeOddsDetail

import (
	"match-spider/util/boltdb"
	"github.com/boltdb/bolt"
	"fmt"
	"strings"
	"github.com/gocolly/colly"
	"time"
	"math/rand"
	"match-forecast/util/queue"
	"encoding/json"
)
var failedEuropeOddsDetail=false
var failedTimesEuropeOddsDetail=1

func europeOddsDetailSpider(dbKey string,bucket string,matchId string,id string,isRepeat bool)  {

	url:="http://121.10.245.46:8072/phone/1x2EuroDetail.aspx?OddsID="+id+"&ScheID="+matchId+"&an=iosQiuTan&av=6.5&from=2&lang=0&r="
	c := colly.NewCollector()
	c.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"

	c.OnResponse(func(response *colly.Response) {
		content:=string(response.Body)
		if strings.Compare(strings.TrimSpace(content),"")==0{
			//请求失败
			queue.EnqueueString("./data_schedule/europeOddsDetail",bucket+"^"+matchId+"^"+id)
			failedEuropeOddsDetail=true
			if isRepeat{
				failedTimesEuropeOddsDetail++
			}

		}else{
			boltdb.Put(dbKey,bucket,matchId+"-"+id,content)
		}

	})

	// Before making a request print "Visiting ..."
	c.OnRequest(func(r *colly.Request) {
		fmt.Println("Visiting", r.URL.String())
	})
	c.OnError(func(r *colly.Response, err error) {
		fmt.Println("Error Request URL:", r.Request.URL)
		queue.EnqueueString("./data_schedule/europeOddsDetail",id)
		failedEuropeOddsDetail=true
		if isRepeat{
			failedTimesEuropeOddsDetail++
		}
	})

	c.Visit(url)
}
/**
亚赔
 */
func europeOddsDetailFailProcess(){
	if failedEuropeOddsDetail{
		//休眠
		time.Sleep(time.Minute*time.Duration(3*failedTimesEuropeOddsDetail))
	}
	data:=queue.Dequeue("./data_schedule/europeOddsDetail")

	if data==nil{
		return
	}
	failedEuropeOddsDetail=false
	s:=strings.Split(string(data.Value),"^")

	if(len(s)<2){
		europeOddsDetailFailProcess()
		return
	}
	europeOddsDetailSpider("europeOddsDetail",s[0],s[1],s[2],true)
	seed:=200+rand.Intn(300)
	time.Sleep(time.Millisecond*time.Duration(seed))
	europeOddsDetailFailProcess()
}
func oddsDetail(league string,matchId string)  {
	boltdb.Get("europe",league,matchId, func(data string) {
		if !strings.Contains(data,"威廉希尔(英国)"){
			return
		}
		europeSlice := make([]string, 0)
		json.Unmarshal([]byte(data), &europeSlice)
		for _, v := range europeSlice {
			d := strings.Split(v, "|")
			size:=len(d)
			oddsId:=d[1]
			if d[size-3]=="威廉希尔(英国)"{
				europeOddsDetailSpider("europeOddsDetail",league,matchId,oddsId,false)
				if failedEuropeOddsDetail{
					failedEuropeOddsDetail=false
					time.Sleep(time.Second*90)
				}else{
					seed:=200+rand.Intn(300)
					time.Sleep(time.Millisecond*time.Duration(seed))
				}
				break
			}

		}

	})
}
func Fetch()  {

	boltdb.ScanTx("matchs", func(tx *bolt.Tx) {

		tx.ForEach(func(name []byte, b *bolt.Bucket) error {

			b.ForEach(func(k, v []byte) error {
				value:=string(v)
				s:=strings.Split(value,"^")

				europeOddsDetailOdds:=strings.TrimSpace(s[7])
				underOverOdds:=strings.TrimSpace(s[8])
				if europeOddsDetailOdds!=""&&underOverOdds!=""{
					//抓取
					league:=strings.TrimSpace(s[1])
					oddsDetail(league,string(k))
				}
				return nil
			})
			return nil
		})

	})

	fmt.Println("================= queue begin =================")
	//处理失败记录
	europeOddsDetailFailProcess()

}
